--[[
Author: Blus
Time:2020.11.09
Desc:breed node for pet
]]

require "Common/define"
require "Logic/PetManager"

local PetBreedNode = Class("PetBreedNode")
function PetBreedNode:ctor()
    self.AddPetType = --框中是否添加宠物
    {
        AddPet = 0,
        NoAdd = 1,
    }
end

function PetBreedNode:Init(obj)
    self.titleText = obj:GetChild("title")
    self.stateController = obj:GetController("state");
    self.stateController.selectedIndex = 1;

    PetBreedNode.titleText = self.titleText;
    --self.leftPartsList = obj:GetChild("Com_MyPetBody"):GetChild("List_MyPetBody");
    --self.leftListShow =  obj:GetChild("Com_MyPetBody"):GetController("select");
    --self.leftListShow.selectedIndex = 0;
    self.leftBreedPet = obj:GetChild("Left")
    self.leftPlayerName = self.leftBreedPet:GetChild("PlayerName")
    self.leftLevel = self.leftBreedPet:GetChild("PetLevel");
    self.Model_TemplatePet = self.leftBreedPet:GetChild("Model_Pet")
    self.leftPetName = self.leftBreedPet:GetChild("PetName")
    self.leftTypeName = self.leftBreedPet:GetChild("TypeName")
    self.leftTypeName.text = getLanguage("PetMating_MutateTitle") --"模板体"
    self.leftAddController = self.leftBreedPet:GetController("AddPetType")

    self.rightBreedPet = obj:GetChild("Right")
    self.rightPartsList = obj:GetChild("List_ChangePart");
    --self.rightListShow =  obj:GetChild("Com_OtherPetBody"):GetController("select");
    --self.rightListShow.selectedIndex = 0;
    self.rightLevel = self.rightBreedPet:GetChild("PetLevel");
    self.rightPlayerName = self.rightBreedPet:GetChild("PlayerName")
    self.Model_MutatePet = self.rightBreedPet:GetChild("Model_Pet")
    self.rightPetName = self.rightBreedPet:GetChild("PetName")
    self.rightTypeName = self.rightBreedPet:GetChild("TypeName")
    self.rightTypeName.text = getLanguage("PetMating_TemplateTitle") --"拟变体"
    self.rightAddController = self.rightBreedPet:GetController("AddPetType")

    --自我拟变
    self.Btn_Mating = obj:GetChild("Btn_Mating")
    self.Btn_Mating:GetChild("title").text = getLanguage("PetMating_Btn_Mutate")
    self.Btn_Preview = obj:GetChild("Btn_Preview")
    self.Btn_Preview:GetChild("title").text = getLanguage("PetMating_Btn_Preview")
    self.Btn_QuickMating = obj:GetChild("allSkip")--快速进化选择
    self.Btn_OneClick = obj:GetChild("Btn_OneClick")--一键选择飞飞
    --obj:GetChild("Txt_TypeName").text = getLanguage("PetMating_Txt_MutatePet")
    PetManager.lockParts = {};
    self:RefreshMatingPage()
end

function PetBreedNode:AddEvent()
    self.Btn_Preview.onClick:Add(self.onClickPreview)
    self.Btn_QuickMating.onClick:Add(function ()
        PetManager.isQuickMating = self.Btn_QuickMating.selected;
    end)
    self.Btn_Mating.onClick:Add(function() self:OnClickMating() end)
    self.Btn_OneClick.onClick:Add(function()
        self:OnClickOneKeyChoose();
    end)
    self.leftBreedPet.onClick:Add(self.OnLeftClick)
    self.rightBreedPet.onClick:Add(self.OnRightClick)
    ListenEvent(Config.EventType.SelectPet, self.OnChangeSelectedPet, self)
    ListenEvent(Config.EventType.RefreshPetMating, self.OnRefreshPetMating, self)
    ListenEvent(Config.EventType.RefreshPetCancelMating, self.RefreshPetCancelMating, self)
    ListenEvent(Config.EventType.RefreshPetCancelMating, self.RefreshPetCancelMating, self)
end

function PetBreedNode:RemoveEvent()
    self.Btn_Preview.onClick:Clear()
    self.Btn_Mating.onClick:Clear()
    self.Btn_OneClick.onClick:Clear()
    self.leftBreedPet.onClick:Clear()
    self.rightBreedPet.onClick:Clear()

    CloseEvent(Config.EventType.SelectPet, self.OnChangeSelectedPet, self)
    CloseEvent(Config.EventType.RefreshPetMating, self.OnRefreshPetMating, self)
    CloseEvent(Config.EventType.RefreshPetCancelMating, self.RefreshPetCancelMating, self)
    CloseEvent(Config.EventType.RefreshPetCancelMating, self.RefreshPetCancelMating, self)

    self:removeTemplateModel()
    self:removeMutateModel()
end

function PetBreedNode:OnRefreshPetMating()
    self:RefreshMatingPage()
end
function PetBreedNode:RefreshPetCancelMating()
    self:RefreshMatingPage()
end

function PetBreedNode:OnLeftClick()
    PetManager.IsTemplatePet = true
    PetManager.TemplatePetId = 0
    showUI(PanelNames.PetSelect)
end

function PetBreedNode:OnRightClick()
    PetManager.IsTemplatePet = false
    PetManager.MutatePetId = 0
    showUI(PanelNames.PetSelect)
end

-- 1：自我拟变
function PetBreedNode:RefreshMatingPage()
    local moneys = decodeJsonStrToTabel(G.dataTable["t_global"]["232"]["f_string_value"])
    self.titleText.text = moneys[table.getn(PetManager.lockParts)] or 0;
    --self.leftListShow.selectedIndex = 0;
    --self.rightListShow.selectedIndex = 0;
    self.stateController.selectedIndex = 1;

    local _leftAddPetType = self.AddPetType.NoAdd
    if PetManager.TemplatePetId ~= 0 then
        _leftAddPetType = self.AddPetType.AddPet
    end
    self.leftAddController.selectedIndex = _leftAddPetType
    local _rightAddPetType = self.AddPetType.NoAdd
    if PetManager.MutatePetId ~= 0 then
        _rightAddPetType = self.AddPetType.AddPet
    end
    self.rightAddController.selectedIndex = _rightAddPetType

    self:OnChangeSelectedPet()
end
function PetBreedNode:removeTemplateModel()
    if self.TemplatePetModelGO then
        destroy(self.TemplatePetModelGO)
    end
    self.TemplatePetModelGO = nil
    PetManager.TemplatePetId = 0;
end
function PetBreedNode:removeMutateModel()
    if self.MutatePetModelGO then
        destroy(self.MutatePetModelGO)
    end
    self.MutatePetModelGO = nil
    PetManager.MutatePetId = 0
end

function PetBreedNode:OnChangeSelectedPet()
    local selectedIndex = self.AddPetType.NoAdd
    local petInfo = nil
    if PetManager.TemplatePetId ~= 0 then
        petInfo = PetManager.GetPetInfoByPetId(PetManager.TemplatePetId)
        if petInfo then
            selectedIndex = self.AddPetType.AddPet
            self.leftPetName.text = petInfo.petName
            self.leftLevel.text = getLanguage("PetMerge_Level") .. PetManager.EvoLevel;
        end
    else
        selectedIndex = self.AddPetType.NoAdd
        self:removeTemplateModel()
    end
    self.leftAddController.selectedIndex = selectedIndex

    if PetManager.MutatePetId ~= 0 then
        PetManager.lockParts = {};
        petInfo = PetManager.GetPetInfoByPetId(PetManager.MutatePetId)
        if petInfo then
            selectedIndex = self.AddPetType.AddPet
            self.rightPetName.text = petInfo.petName
            self.rightLevel.text = getLanguage("PetMerge_Level") .. PetManager.EvoLevel;
        end
    else
        selectedIndex = self.AddPetType.NoAdd
        self:removeMutateModel()
    end
    self.rightAddController.selectedIndex = selectedIndex

    local _touchable = PetManager.TemplatePetId ~= 0 and PetManager.MutatePetId ~= 0
    self.Btn_Mating.touchable = _touchable
    self.Btn_Mating:GetController("gray").selectedIndex = _touchable and 0 or 1;
    self.Btn_Mating.enabled = _touchable
    self.Btn_Preview.touchable = _touchable
    self.Btn_Preview.enabled = _touchable

    self:showTemplatePetModel()
    self:showMutatePetModel()
end

function PetBreedNode:onClickPreview()
    if PetManager.MutatePetId ~= 0 and PetManager.TemplatePetId ~= 0 then
        --点击预览
        -- TAManager.TrackByDictionary("pet_click_preview")
        showUI(PanelNames.Page_PetMatingPreview)
    end
end

function PetBreedNode:OnClickOneKeyChoose()
    PetManager.IsTemplatePet = false
    for i = 1, #PetManager.PetInfoList do
        local petInfo = PetManager.PetInfoList[i];
        local _isNormal = PetManager.CheckPetCanTemplate(petInfo);
        if _isNormal and not PetManager.IsTemplatePet then
            --本体
            PetManager.TemplatePetId = petInfo.petId
            PetManager.IsTemplatePet = true
        elseif _isNormal and PetManager.IsTemplatePet then
            --拟变体
            PetManager.MutatePetId = petInfo.petId
        end

        if PetManager.MutatePetId ~= 0 and PetManager.TemplatePetId ~= 0 then
            --选择完毕
            self:OnChangeSelectedPet();
            return
        end
        if i == #PetManager.PetInfoList and (PetManager.MutatePetId == 0 or PetManager.TemplatePetId == 0) then
        --无法匹配
            PetManager.MutatePetId = 0;
            PetManager.TemplatePetId = 0;
            UISysTips.AddMsg(getLanguage("ErrorCode_190003"));
        end
    end
end

function PetBreedNode:OnClickMating()
    local moneys = decodeJsonStrToTabel(G.dataTable["t_global"]["232"]["f_string_value"])
    local moneyNum = moneys[table.getn(PetManager.lockParts)] or 0;
    if moneyNum > ItemManager.getCurrencyCountByModelId(CurrencyEnum.GOLD) then
        --红魔石不足
        UISysTips.AddMsg(getLanguage("Character_Tips7"))
        return
    end
    if PetManager.MutatePetId ~= 0 and PetManager.TemplatePetId ~= 0 then
        --点击进化
        -- TAManager.TrackByDictionary("pet_click_mating")
        if self.Btn_QuickMating.selected then
            --快速进化
            local sendLockParts = {};
            for i, v in pairs(PetManager.lockParts) do
                table.insert(sendLockParts, v.type);
            end
            PetHandler.ReqSelfMating(PetManager.TemplatePetId, PetManager.MutatePetId, sendLockParts)
        else
            showUI(PanelNames.Page_PetMatingPreview)
        end
    end
    --if PetManager.TemplatePetId ~= 0 and PetManager.MutatePetId ~= 0 then
    --    PetHandler.ReqSelfMating(PetManager.TemplatePetId,PetManager.MutatePetId)
    --end
end

--显示宠物模型
function PetBreedNode:showTemplatePetModel()
    if PetManager.TemplatePetId == 0 then
        return
    end

    local _petInfo = PetManager.GetPetInfoByPetId(PetManager.TemplatePetId)
    if _petInfo and #_petInfo.genes == PetManager.PetPart.Ornament then
        local _petModelInfo = {}
        _petModelInfo.parentGO = self.Model_TemplatePet
        _petModelInfo.petId = _petInfo.petId
        --初始化部件显示
        --self.leftPartsList.itemRenderer = self.rendererLeftPart;
        --self.leftPartsList.numItems = #_petInfo.genes;
        --self.leftListShow.selectedIndex = 1;

        if self.TemplatePetModelGO and self.TemplateGoWrapper then
            _petModelInfo.modelGO = self.TemplatePetModelGO
            _petModelInfo.modelWrapper = self.TemplateGoWrapper
            PetManager.PetModelRefresh(_petModelInfo, _petInfo.genes, true)
        else
            resMgr:LoadModelPrefab(PetManager.PetModelPrefab, function(go)
                self.TemplatePetModelGO = newObject(go)

                local com = self.TemplatePetModelGO:GetComponent("SkeletonGraphic")

             if self.TemplatePetModelGO and com then
                 com.material = resMgr.Pet_Copy_Mat
                 com.material:SetFloat("_StencilComp",8)
                 com.material:SetFloat("_Stencil",1);
             end

                _petModelInfo.modelGO = self.TemplatePetModelGO
                _petModelInfo.modelWrapper = GoWrapper.New()
                PetManager.PetModelFirstSet(_petModelInfo, _petInfo.genes, true, Vector3.New(0, 0, 0), Vector3.New(1.2, 1.2, 1))
                if self.TemplateGoWrapper then
                    self.TemplateGoWrapper:Dispose()
                end
                self.TemplateGoWrapper = _petModelInfo.modelWrapper
            end)
        end
    end
end

--function PetBreedNode.rendererLeftPart(idx,obj)
--    local _petInfo = PetManager.GetPetInfoByPetId(PetManager.TemplatePetId)
--    PetBreedNode:initParts(obj,_petInfo.genes[idx+1]);
--
--end

function PetBreedNode.rendererRightPart(idx, obj)
    local lockController = obj:GetController("isLock");
    lockController.selectedIndex = PetManager.checkTypeIsCheck(idx + 1) and 1 or 0;
    local _petInfo = PetManager.GetPetInfoByPetId(PetManager.MutatePetId)
    PetBreedNode:initParts(obj, _petInfo.genes[idx + 1]);
end

function PetBreedNode:initParts(go, data)
    local ctrlItem = CtrlManager.GetCtrl(PanelNames.PetPartItem);
    ctrlItem.initData(go, data, function(cfg)
        PetBreedNode.lockPart(cfg, go)
        local moneys = decodeJsonStrToTabel(G.dataTable["t_global"]["232"]["f_string_value"])
        PetBreedNode.titleText.text = moneys[table.getn(PetManager.lockParts)] or 0;
    end);
end

function PetBreedNode.lockPart(cfg, obj)
    local id = cfg.f_GeneId
    if id == nil then
        return
    end

    local lockController = obj:GetController("isLock");
    if PetManager.lockParts == nil then
        PetManager.lockParts = {};
    end
    if PetManager.lockParts[id] == nil then
        if table.getn(PetManager.lockParts) >= table.getn(decodeJsonStrToTabel(G.dataTable["t_global"]["232"]["f_string_value"])) then
            UISysTips.AddMsg(getLanguage("PetApply_LockFull")) --已经锁定了12个部位
            return
        end
        --锁定
        local data = {}
        data.id = id;
        data.type = cfg.f_ChromosomeId;
        PetManager.lockParts[id] = data;
        lockController.selectedIndex = 1;
    else
        --解除锁定
        PetManager.lockParts[id] = nil;
        lockController.selectedIndex = 0;
    end
    --table.insert(PetManager.lockParts ,id);

end

function PetBreedNode:showMutatePetModel()
    if PetManager.MutatePetId == 0 then
        return
    end

    local _petInfo = PetManager.GetPetInfoByPetId(PetManager.MutatePetId)

    if _petInfo and #_petInfo.genes == PetManager.PetPart.Ornament then
        local _petModelInfo = {}
        _petModelInfo.parentGO = self.Model_MutatePet
        _petModelInfo.petId = _petInfo.petId
        self.rightPartsList.itemRenderer = self.rendererRightPart;
        self.rightPartsList.numItems = #_petInfo.genes;
        --self.rightListShow.selectedIndex = 1;
        local moneys = decodeJsonStrToTabel(G.dataTable["t_global"]["232"]["f_string_value"])

        PetBreedNode.titleText.text = moneys[table.getn(PetManager.lockParts)] or 0;
        self.stateController.selectedIndex = 0;

        if self.MutatePetModelGO then
            _petModelInfo.modelGO = self.MutatePetModelGO
            _petModelInfo.modelWrapper = self.MutateGoWrapper
            PetManager.PetModelRefresh(_petModelInfo, _petInfo.genes, true)
        else
            resMgr:LoadModelPrefab(PetManager.PetModelPrefab, function(go)
                self.MutatePetModelGO = newObject(go)

                local com = self.MutatePetModelGO:GetComponent("SkeletonGraphic")

             if self.MutatePetModelGO and com then
                 com.material = resMgr.Pet_Copy_Mat
                 com.material:SetFloat("_StencilComp",8)
                 com.material:SetFloat("_Stencil",1);
             end

                _petModelInfo.modelGO = self.MutatePetModelGO
                _petModelInfo.modelWrapper = GoWrapper.New()
                PetManager.PetModelFirstSet(_petModelInfo, _petInfo.genes, true, Vector3.New(0, 0, 0), Vector3.New(1.2, 1.2, 1))
                if self.MutateGoWrapper then
                    self.MutateGoWrapper:Dispose()
                end
                self.MutateGoWrapper = _petModelInfo.modelWrapper
            end)
        end
    end
end

-- 自我拟变 End
return PetBreedNode